package com.example.util;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

public class BCryptPasswordGenerator {

    private static final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 生成加密的 BCrypt 密码
     *
     * @param rawPassword 明文密码
     * @return 加密后的密码
     */
    public static String generateBCryptPassword(String rawPassword) {
        return passwordEncoder.encode(rawPassword);
    }

    /**
     * 验证明文密码是否与加密后的密码匹配
     *
     * @param rawPassword 明文密码
     * @param encryptedPassword 加密后的密码
     * @return 如果匹配返回 true，否则返回 false
     */
    public static boolean validatePassword(String rawPassword, String encryptedPassword) {
        return passwordEncoder.matches(rawPassword, encryptedPassword);
    }

    public static void main(String[] args) {
        test1();
        test2();
    }

    private static void test1() {
        // 示例：生成加密密码
        String rawPassword = "password123";
        String encryptedPassword = generateBCryptPassword(rawPassword);
        System.out.println("Encrypted password: " + encryptedPassword);
    }

    private static void test2() {
        // 示例：验证密码
        String rawPassword = "password123";
        String encryptedPassword = "$2a$10$DowQe/TWRRtPojPeLcsbiOpTCz2TfFbwxLCkYV8Pf16BQYjfxTLzm"; // 示例加密密码
        boolean isValid = validatePassword(rawPassword, encryptedPassword);
        System.out.println("Password is valid: " + isValid);
    }

}
